<template>
  <PageContainer>
    <!-- 未登录状态：显示注册/登录表单 -->
    <div v-if="!isAuthenticated" class="auth-section">
      <div class="auth-container">
        <div class="auth-tabs">
          <button
            class="tab-button"
            :class="{ active: activeTab === 'login' }"
            @click="activeTab = 'login'"
          >
            登录
          </button>
          <button
            class="tab-button"
            :class="{ active: activeTab === 'register' }"
            @click="activeTab = 'register'"
          >
            注册
          </button>
        </div>

        <!-- 登录表单 -->
        <form v-if="activeTab === 'login'" class="auth-form" @submit.prevent="handleLogin">
          <div class="form-group">
            <label>用户名</label>
            <input v-model="loginForm.username" type="text" required placeholder="请输入用户名" />
          </div>
          <div class="form-group">
            <label>密码</label>
            <input
              v-model="loginForm.password"
              type="password"
              required
              placeholder="请输入密码"
            />
          </div>
          <button type="submit" class="submit-button" :disabled="authState.loading">
            {{ authState.loading ? '登录中...' : '登录' }}
          </button>
          <p v-if="authState.error" class="error-message">{{ authState.error }}</p>
        </form>

        <!-- 注册表单 -->
        <form v-if="activeTab === 'register'" class="auth-form" @submit.prevent="handleRegister">
          <div class="form-group">
            <label>用户名</label>
            <input v-model="registerForm.username" type="text" required placeholder="请输入用户名" />
          </div>
          <div class="form-group">
            <label>密码</label>
            <input
              v-model="registerForm.password"
              type="password"
              required
              placeholder="请输入密码（至少6位）"
              minlength="6"
            />
          </div>
          <div class="form-group">
            <label>个人简介（可选）</label>
            <textarea
              v-model="registerForm.bio"
              placeholder="介绍一下自己..."
              rows="3"
            ></textarea>
          </div>
          <button type="submit" class="submit-button" :disabled="authState.loading">
            {{ authState.loading ? '注册中...' : '注册' }}
          </button>
          <p v-if="authState.error" class="error-message">{{ authState.error }}</p>
        </form>
      </div>
    </div>

    <!-- 已登录状态：显示用户信息和个人内容 -->
    <div v-else class="user-profile">
      <!-- 用户基本信息卡片 -->
      <div class="profile-header">
        <div class="avatar-section">
          <div class="avatar">
            <span v-if="!userInfo.avatar">{{ userInfo.username?.[0]?.toUpperCase() || 'U' }}</span>
            <img v-else :src="userInfo.avatar" :alt="userInfo.username" />
          </div>
          <div class="user-info">
            <h2>{{ userInfo.username }}</h2>
            <p v-if="userInfo.bio" class="bio">{{ userInfo.bio }}</p>
            <p v-else class="bio-placeholder">暂无个人简介</p>
            <div class="user-meta">
              <span>注册时间：{{ formatDate(userInfo.created_at) }}</span>
            </div>
          </div>
        </div>
        <button class="logout-button" @click="handleLogout">退出登录</button>
      </div>

      <!-- 统计信息 -->
      <div class="stats-grid">
        <div class="stat-card">
          <div class="stat-value">{{ userPosts.length }}</div>
          <div class="stat-label">发布的帖子</div>
        </div>
        <div class="stat-card">
          <div class="stat-value">{{ userComments.length }}</div>
          <div class="stat-label">发表的评论</div>
        </div>
        <div class="stat-card">
          <div class="stat-value">{{ totalLikes }}</div>
          <div class="stat-label">获得点赞</div>
        </div>
      </div>

      <!-- 内容标签页 -->
      <div class="content-tabs">
        <button
          class="tab-button"
          :class="{ active: activeContentTab === 'posts' }"
          @click="activeContentTab = 'posts'"
        >
          我的帖子 ({{ userPosts.length }})
        </button>
        <button
          class="tab-button"
          :class="{ active: activeContentTab === 'comments' }"
          @click="activeContentTab = 'comments'"
        >
          我的评论 ({{ userComments.length }})
        </button>
      </div>

      <!-- 我的帖子列表 -->
      <AsyncState
        v-if="activeContentTab === 'posts'"
        :loading="postsLoading"
        :error="postsError"
        :isEmpty="!userPosts.length"
        emptyMessage="你还没有发布过帖子，快去讨论区发帖吧！"
        :retry="fetchUserPosts"
      >
        <div class="posts-list">
          <InfoCard
            v-for="post in userPosts"
            :key="post.id"
            :title="post.title"
            :description="truncateText(post.content, 120)"
            :meta="[
              { label: '发布时间', value: formatDate(post.created_at) },
              { label: '点赞', value: post.likes ?? 0 },
              { label: '回复', value: post.replies?.length ?? 0 },
            ]"
            :tags="post.tags"
            :to="`/forum/${post.id}`"
            clickable
          />
        </div>
      </AsyncState>

      <!-- 我的评论列表 -->
      <AsyncState
        v-if="activeContentTab === 'comments'"
        :loading="commentsLoading"
        :error="commentsError"
        :isEmpty="!userComments.length"
        emptyMessage="你还没有发表过评论"
        :retry="fetchUserComments"
      >
        <div class="comments-list">
          <div v-for="comment in userComments" :key="comment.id" class="comment-item">
            <div class="comment-header">
              <span class="comment-target">
                {{ getCommentTarget(comment) }}
              </span>
              <span class="comment-date">{{ formatDate(comment.created_at) }}</span>
            </div>
            <p class="comment-content">{{ comment.content }}</p>
            <RouterLink
              v-if="comment.target_type === 'post'"
              :to="`/forum/${comment.target_id}`"
              class="view-link"
            >
              查看帖子 →
            </RouterLink>
          </div>
        </div>
      </AsyncState>
    </div>
  </PageContainer>
</template>

<script setup>
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import PageContainer from '../components/PageContainer.vue'
import AsyncState from '../components/AsyncState.vue'
import InfoCard from '../components/InfoCard.vue'
import { useAuth } from '../composables/useAuth'
import { register, getCurrentUser, getPosts, getComments } from '../api/client'
import { useAsyncData } from '../composables/useAsyncData'
import { formatDate, truncateText } from '../utils/formatters'

const router = useRouter()
const authState = useAuth()
const { user, isAuthenticated, login, logout } = authState

const activeTab = ref('login')
const activeContentTab = ref('posts')
const userInfo = ref({})

const loginForm = ref({
  username: '',
  password: '',
})

const registerForm = ref({
  username: '',
  password: '',
  bio: '',
})

// 获取所有帖子，然后过滤出当前用户的
const {
  data: allPosts,
  loading: postsLoading,
  error: postsError,
  execute: fetchUserPosts,
} = useAsyncData(getPosts, {
  initialValue: [],
  transform: (data) => data?.items ?? [],
})

// 获取所有评论，然后过滤出当前用户的
const {
  data: allComments,
  loading: commentsLoading,
  error: commentsError,
  execute: fetchUserComments,
} = useAsyncData(getComments, {
  initialValue: [],
  transform: (data) => data?.items ?? [],
})

// 过滤出当前用户的帖子
const userPosts = computed(() => {
  if (!user.value?.username) return []
  return allPosts.value
    .filter((post) => post.author === user.value.username)
    .sort((a, b) => new Date(b.created_at || 0) - new Date(a.created_at || 0))
})

// 过滤出当前用户的评论
const userComments = computed(() => {
  if (!user.value?.id) return []
  return allComments.value
    .filter((comment) => comment.author_id === user.value.id)
    .sort((a, b) => new Date(b.created_at || 0) - new Date(a.created_at || 0))
})

// 计算总点赞数
const totalLikes = computed(() => {
  return userPosts.value.reduce((sum, post) => sum + (post.likes || 0), 0)
})

// 获取评论目标信息
function getCommentTarget(comment) {
  if (comment.target_type === 'post') {
    const post = allPosts.value.find((p) => p.id === comment.target_id)
    return post ? `回复帖子：${post.title}` : `回复帖子 #${comment.target_id}`
  }
  return `评论 #${comment.target_id}`
}

// 处理登录
async function handleLogin() {
  try {
    await login(loginForm.value)
    await loadUserInfo()
    await fetchUserPosts()
    await fetchUserComments()
    router.push('/user')
  } catch (error) {
    console.error('登录失败', error)
  }
}

// 处理注册
async function handleRegister() {
  if (registerForm.value.password.length < 6) {
    authState.state.error = '密码长度至少为6位'
    return
  }

  try {
    const response = await register({
      username: registerForm.value.username,
      password: registerForm.value.password,
      bio: registerForm.value.bio || undefined,
    })

    if (response?.token && response?.user) {
      // 注册成功后自动登录
      authState.state.user = response.user
      authState.state.token = response.token
      // 保存到localStorage
      const { saveAuthSession } = await import('../api/client')
      saveAuthSession({
        token: response.token,
        user: response.user,
      })

      await loadUserInfo()
      await fetchUserPosts()
      await fetchUserComments()
      activeTab.value = 'login'
      registerForm.value = { username: '', password: '', bio: '' }
      router.push('/user')
    }
  } catch (error) {
    console.error('注册失败', error)
    authState.state.error = error?.message || '注册失败，请稍后再试'
  }
}

// 处理退出登录
function handleLogout() {
  logout()
  userInfo.value = {}
  router.push('/user')
}

// 加载用户信息
async function loadUserInfo() {
  if (!isAuthenticated.value) return
  try {
    const currentUser = await getCurrentUser()
    userInfo.value = currentUser || user.value || {}
  } catch (error) {
    console.error('获取用户信息失败', error)
    userInfo.value = user.value || {}
  }
}

onMounted(async () => {
  if (isAuthenticated.value) {
    await loadUserInfo()
    await fetchUserPosts()
    await fetchUserComments()
  }
})
</script>

<style scoped>
.auth-section {
  display: flex;
  justify-content: center;
  padding: 40px 20px;
}

.auth-container {
  width: 100%;
  max-width: 420px;
  background: #fff;
  border-radius: 16px;
  padding: 32px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.auth-tabs {
  display: flex;
  gap: 8px;
  margin-bottom: 24px;
  border-bottom: 2px solid #ebeef5;
}

.tab-button {
  flex: 1;
  padding: 12px;
  border: none;
  background: transparent;
  font-size: 16px;
  font-weight: 500;
  color: #909399;
  cursor: pointer;
  transition: all 0.3s ease;
  border-bottom: 2px solid transparent;
  margin-bottom: -2px;
}

.tab-button:hover {
  color: #409eff;
}

.tab-button.active {
  color: #409eff;
  border-bottom-color: #409eff;
}

.auth-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  font-size: 14px;
  font-weight: 500;
  color: #606266;
}

.form-group input,
.form-group textarea {
  padding: 10px 14px;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  font-size: 14px;
  transition: border-color 0.3s ease;
}

.form-group input:focus,
.form-group textarea:focus {
  outline: none;
  border-color: #409eff;
  box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.1);
}

.form-group textarea {
  resize: vertical;
  font-family: inherit;
}

.submit-button {
  padding: 12px;
  background: #409eff;
  color: #fff;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: background 0.3s ease;
}

.submit-button:hover:not(:disabled) {
  background: #337ecc;
}

.submit-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.error-message {
  margin: 0;
  padding: 10px;
  background: #fef0f0;
  color: #f56c6c;
  border-radius: 6px;
  font-size: 14px;
}

.user-profile {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.profile-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 24px;
  padding: 24px;
  background: linear-gradient(135deg, rgba(64, 158, 255, 0.1), rgba(103, 194, 58, 0.1));
  border-radius: 16px;
  border: 1px solid rgba(64, 158, 255, 0.2);
}

.avatar-section {
  display: flex;
  gap: 20px;
  align-items: flex-start;
}

.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background: linear-gradient(135deg, #409eff, #67c23a);
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 32px;
  font-weight: 600;
  flex-shrink: 0;
  overflow: hidden;
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.user-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.user-info h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f2d3d;
}

.bio {
  margin: 0;
  color: #606266;
  line-height: 1.6;
  max-width: 500px;
}

.bio-placeholder {
  margin: 0;
  color: #909399;
  font-style: italic;
}

.user-meta {
  display: flex;
  gap: 16px;
  font-size: 13px;
  color: #909399;
}

.logout-button {
  padding: 8px 16px;
  background: #f56c6c;
  color: #fff;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  cursor: pointer;
  transition: background 0.3s ease;
}

.logout-button:hover {
  background: #f45050;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.stat-card {
  padding: 20px;
  background: #fff;
  border-radius: 12px;
  border: 1px solid #ebeef5;
  text-align: center;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
  border-color: rgba(64, 158, 255, 0.3);
}

.stat-value {
  font-size: 32px;
  font-weight: 700;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.content-tabs {
  display: flex;
  gap: 8px;
  border-bottom: 2px solid #ebeef5;
  padding-bottom: 0;
}

.posts-list,
.comments-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.comment-item {
  padding: 20px;
  background: #fff;
  border-radius: 12px;
  border: 1px solid #ebeef5;
  display: flex;
  flex-direction: column;
  gap: 12px;
  transition: all 0.3s ease;
}

.comment-item:hover {
  border-color: rgba(64, 158, 255, 0.3);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 12px;
}

.comment-target {
  font-size: 14px;
  font-weight: 500;
  color: #409eff;
}

.comment-date {
  font-size: 12px;
  color: #909399;
  white-space: nowrap;
}

.comment-content {
  margin: 0;
  color: #606266;
  line-height: 1.6;
  font-size: 14px;
}

.view-link {
  align-self: flex-start;
  font-size: 13px;
  color: #409eff;
  text-decoration: none;
  font-weight: 500;
}

.view-link:hover {
  text-decoration: underline;
}

@media (max-width: 768px) {
  .profile-header {
    flex-direction: column;
    align-items: stretch;
  }

  .logout-button {
    align-self: flex-start;
  }

  .stats-grid {
    grid-template-columns: 1fr;
  }

  .avatar-section {
    flex-direction: column;
    align-items: center;
    text-align: center;
  }
}
</style>
